<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/5/15 15:37
 * Email: <594652523@qq.com>
 */

namespace App\Console\Commands;

use App\Models\Absence;
use App\Models\CourseOrder;
use App\Models\CourseSection;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AbsenceAdd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'absence';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '课程缺勤添加';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        //增加课程缺勤（章节已打卡，已请假以及章节时间在1小时内可以打卡的除外）
        CourseOrder::where('status', 2)->orwhere('status', 3)->from('course_order')->orderBy('id')->chunk(100, function ($list) {
            foreach ($list as $item) {
                $sectionList = CourseSection::where('course_id', $item['course_id'])
                    //打卡的
                    ->whereNotIn('id', function ($q) use ($item) {
                        $q->where('user_id', $item['user_id'])->where('course_id', $item['course_id'])->select('course_section_id')->from('course_duty');
                    })
                    //请假的
                    ->whereNotIn('id', function ($q) use ($item) {
                        $q->where('user_id', $item['user_id'])->where('course_id', $item['course_id'])->select('course_section_id')->from('leave');
                    })
                    //未到下课时间还能打卡的
                    ->where('end_time', '<', time() - 15 * 60)
                    //已经有缺勤记录的
                    ->whereNotIn('id', function ($q) use ($item) {
                        $q->where('user_id', $item['user_id'])->where('course_id', $item['course_id'])->select('course_section_id')->from('absence');
                    })
                    ->get(['id', 'class_time', 'begin_time', 'end_time'])->toArray();
                if (!empty($sectionList)) {
                    foreach ($sectionList as $value) {
                        Absence::create(['user_id' => $item['user_id'], 'course_order_id' => $item['id'], 'course_id' => $item['course_id'], 'course_section_id' => $value['id']]);
                        $this->info('订单' . $item['id'] . '用户' . $item['user_id'] . '课程' . $item['course_id'] . '课程章节' . $value['id'] . '缺勤');
                        Log::info('订单' . $item['id'] . '用户' . $item['user_id'] . '课程' . $item['course_id'] . '课程章节' . $value['id'] . '缺勤');
                    }
                }
            }
        });
    }

}
